<?php

namespace App\Repositories;

class UserScoreRepository
{
    public function getUserScore($user_id)
    {
        $where = ['user_id' => $user_id];
        $data = ['user_id' => $user_id, 'total' => 0, 'balance' => 0];

        return app('model_user_score')->firstOrCreate($where, $data);
    }

    public function getUserScoreBalance($user_id)
    {
        $result = $this->getUserScore($user_id);
        return $result->balance;
    }

    //type: 1道具赠送积分 2兑换积分商城商品扣除积分 3兑换普通气泡 4活动发放积分
    public function sendScore($user_id, $score, $type, $foreign_id = 0, $remark = '')
    {
        $user_score = $this->getUserScore($user_id);
        $score_current = $score + $user_score->balance;
        if ($score_current < 0) {
            return false;
        }
        $update_data['balance'] = $score_current;
        if ($score > 0) {
            $update_data['total'] = $score + $user_score->total;
        }

        $where [] = ['user_id', $user_id];
        if ($score < 0) {
            $where [] = ['balance', '>=', abs($score)];
        }
        $result = app('model_user_score')->where($where)->update($update_data);
        if (!$result) {
            return false;
        }
        app('model_user_score_log')->create([
            'user_id'       => $user_id,
            'score_before'  => $user_score->balance,
            'score_change'  => $score,
            'score_current' => $score_current,
            'type'          => $type,
            'foreign_id'    => $foreign_id,
            'remark'        => $remark,
        ]);

        return true;
    }

    //积分日志 type:1获取2使用
    public function getUserScoreLog($user_id, $type, $page, $perPage)
    {
        $where[] = ['user_id', $user_id];
        if ($type == 1) {
            $where[] = ['score_change', '>', 0];
        } elseif ($type == 2) {
            $where[] = ['score_change', '<', 0];
        }
        $list = app('model_user_score_log')->select(['id', 'score_change', 'remark', 'created_at'])->where($where)->orderBy('id', 'desc')->paginate($perPage, ['*'], '', $page);

        return $list;
    }
}
